<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ApiListTrait;
use App\Helpers\ExcelExportTrait;
use App\Helpers\Trackingmore;
use App\Model\Express;
use App\Model\ExpressCarrier;
use App\Model\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class OrderController extends BaseController
{
    use ApiListTrait,ExcelExportTrait;
    //模型名称
    protected $modelName = "App\Model\Order";

    //创建查询模型
    protected function query()
    {
        return $this->model();
    }

    //实例化模型
    protected function model($id = false)
    {
        return $id ? $this->query()->find($id) : new $this->modelName;
    }

    //模型字段
    protected function modelColumns()
    {
        return $this->model()->tableColumns();
    }
    //发货
    public function delivery(Request $request)
    {
        $ids = $request->input('ids',0);
        $ids = explode(',',$ids);
        $count = DB::table('orders')->whereIn('id',$ids)->where('state','=',1)
            ->where('is_pay','=','yes')
            ->where('is_delivery','=',"no")
            ->update(['state'=>5,'is_delivery'=>"yes"]);

        if ($out_trade_no = $request->input('out_trade_no')){
            $count = DB::table('orders')->where('out_trade_no','=',$out_trade_no)->where('state','=',1)
                ->where('is_pay','=','yes')
                ->where('is_delivery','=',"no")
                ->update(['state'=>5,'is_delivery'=>"yes"]);
        }
        return $this->success(['total'=>$count]);
    }
    //发货
    public function delivery2(Request $request)
    {
        $rules = [
            'out_trade_no' =>[
                'required',
                Rule::exists('orders','out_trade_no')->where(function ($query){
                    $query->where('state',1);
                })
            ] ,
            'code' => 'required',
            'number' => 'required'
        ];

        $messages = [
            'out_trade_no.exists' => '商品已发货，请勿重复',
            'number' => "物流单号必填",
            'code' => "物流公司必选"
        ];

        if (!$this->requestValidate($request->all(),$rules,$messages)){
            return $this->failed($this->error);
        }

        $number = $request->input('number');
        $code = $request->input('code');
        $out_trade_no = $request->input('out_trade_no');
        $c  = Express::where('tracking_number','=',$number)->where('carrier_code','=',$code)
            ->where('out_trade_no','=',$out_trade_no)->count();

        if ($c > 0 )  return $this->failed('已存在，请勿重复添加！');

        $express = Express::firstOrNew(['tracking_number'=>$number,
            'carrier_code'=>$code,
            'out_trade_no'=>$out_trade_no]);



        $order = Order::where('out_trade_no','=',$request->input('out_trade_no'))->first();

        $express->order_id = $order->id;
        $express->title = $order->product_chname?$order->product_chname:'';
        $express->customer_name = $order->username?$order->username:'';

        $order->is_delivery = "yes";
        $order->delivery_time = date('Y-m-d H:i:s');
        $order->state = 5;
        $order->save();

        $express->save();

        ExpressCarrier::addSort($code);

        $t = new Trackingmore();
        $tracking = [
            'title'=>$express->title,
            'customer_name' => $express->customer_name,
            'customer_email' => '',
            'order_id'=>$express->out_trade_no
        ];
        $t->createTracking($express->carrier_code,$express->tracking_number,$tracking);

        return $this->success($express);
    }

    //查物流
    public function queryDelivery($id)
    {
        $order = Order::find($id);

        if (!$order) return $this->notFond();

        $e = Express::where('out_trade_no','=',$order->out_trade_no)
            ->first();

        if (!$e)  return $this->notFond();

        $e->updateTrackingRealTime();

        $e->load('carrier');

        return $this->success($e);

    }

    public function export(Request $request)
    {
        $query = new Order();
        $this->build($query,$request->input('_param'));

        $this->processFilter();//过滤

        $this->processSearch();//搜索

        $this->processSort();//过滤

        $this->processPages();//分页

        $query = $this->processQueryModel;

        $items = $query->orderBy('created_at','desc')->get();

        $rows = $items->map(function ($item){
            $d = [];
            $d['订单号'] = $item->out_trade_no;

            $d['付款人'] = $item->createUser?$item->createUser->name:'';

            $d['商品名称'] = $item->product_chname;
            $d['商品市场价'] = $item->origin_price;
            $d['商品售卖价'] = $item->price;
            $d['商品数量'] = $item->product_chname;
            $d['商品数量'] = $item->quantity;
            $d['订单总金额'] = $item->total_fee;
            $d['运费'] = $item->deliver_fee;

            $d['收件人名称'] = $item->username;
            $d['收件人手机'] = $item->tel_number;
            $d['收件人地址'] = $item->address;
            $d['状态'] = $item->chState;
            $d['下单时间'] = is_object($item->created_at)?$item->created_at->toDateTimeString():$item->created_at;
            $d['买家留言'] = $item->comment;

            return $d;
        });
        $name = "订单-".date('Ymd');

        $style['width'] = array(
            'A' => 30,
            'B' => 20,
            'C' => 30,
            'D' => 20,
            'E' => 15,
            'F' => 15,
            'G' => 15,
            'H' => 15,
            'I' => 15,
            'J' => 20,
            'K' => 25,
            'L' => 50,
            'M' => 15,
            'N' => 20,
            'O' => 55,
        );
        return $this->exportFile($name,$rows,'xlsx',$style);
    }
}
